package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

@Service
public class TokenServiceImpl implements TokenService {
    
    @Autowired
    private TokenDao tokenDao;
    
    @Override
    public Token findTokenByUserEmail(String email) {
        Token token = new Token();
        token.setEmail(email);

        Optional<Token> res = tokenDao.findOne(Example.of(token));
        if (res.isEmpty()) {
            return null;
        } else {
            return res.get();
        }
    }

    @Override
    public String generateTokenByEmailPassword(String email, String password) {

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        byte[] digest = md5.digest((email + password).getBytes(StandardCharsets.UTF_8));

        return DigestUtils.md5DigestAsHex(digest);
//        return new String(Hex.encodeHex(digest));

//        return new String(digest, StandardCharsets.UTF_8);
    }

    @Override
    public Token findToken(String token) {

        Token t = new Token();
        t.setToken(token);

        Optional<Token> one = tokenDao.findOne(Example.of(t));
        if (one.isEmpty()) {
            return null;
        } else {
            return one.get();
        }
    }

    @Override
    public boolean registerUser(String email, String password) {
        String token = generateTokenByEmailPassword(email, password);
        Token tokenObj = new Token();
        tokenObj.setEmail(email);
        tokenObj.setToken(token);

        tokenDao.save(tokenObj);

        return true;
    }
}
